/* eslint-disable no-param-reassign */
import { makeAutoObservable, toJS } from 'mobx';
import * as api from './api';

export default class CcStationGroupStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  _allItems = []; // 所有region的字典项
  cities = []; // 顶级节点
  groups = []; // 所有分组
  _selected = '';
  loading = false;

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  * fetchGroups() {
    this.loading = true;
    try {
      let items = yield api.allItems();
      this._allItems = _.cloneDeep(items);
      this.cities = [...items].filter((item) => (!item.parentId)).sort((a, b) => a.itemId.localeCompare(b.itemId));
      items = items.filter((item) => (item.extras?.group?.value));
      items = items.map((item) => ({ name: item.extras.group.value, city: item.fullId.split(':')[0] }));
      this.groups = _.uniqBy(items, 'name').sort(); // (a, b) => a.name.localeCompare(b.name));
      this._selected = this.groups[0];
      // const oldGroup = this.getGroup(this._selected?.name);
      // this._selected = oldGroup || this.groups[0];

      this.cities.forEach((city) => {
        city.children = this.groupsForCity(city.itemId);
      });
    } finally {
      this.loading = false;
    }
  }

  * _reload(cause) {
    yield this.fetchGroups();
    if (cause) {
      this.selectedName = cause.name;
    }
  }

  * update(group) {
    this.loading = true;
    try {
      const data = this._toItems(group);
      yield api.updateItems(data);
      yield this._reload(group);
    } finally {
      this.loading = false;
    }
  }

  * create(group) {
    yield api.updateItems(this._toItems(group));
    yield this._reload(group);
  }

  * remove(group) {
    yield api.updateItems(toJS(this._toItems(group)));
    yield this._reload();
  }

  * updateGroup() {
    yield api.updateGroup();
    yield this.fetchGroups();
  }

  _toItems(group) { // 组装group为待修改的items列表
    const items = [];
    group.regions.map((itemId) => this._item(itemId)).forEach(({ dictId, itemId, extras }) => items.push({ dictId, itemId, extras: { ...extras, group: { value: group.name } } }));
    if (group.originName) { // 清除旧的分组属性
      this.regionsForGroup(group.originName).forEach(({ dictId, itemId, extras }) => {
        if (!items.some((r) => r.itemId === itemId)) items.push({ dictId, itemId, extras: { ...extras, group: { value: '' } } });
      });
    }
    return _.uniqBy(items, 'itemId');
  }

  _item(itemId) {
    return toJS(this._allItems).find((item) => item.itemId === itemId);
  }

  regionsForGroup(groupName) {
    return toJS(this._allItems).filter((v) => (v.extras?.group?.value === groupName));
  }

  regionsForCity(cityId) { // 获取城市下的所有区域供选择
    return toJS(this._allItems).filter((v) => (v.fullId.match(new RegExp(`^${cityId}:`)))).map((v) => toJS(v));
  }

  getGroup(name) {
    return this.groups.find((v) => (v.name === name));
  }

  groupsForCity(cityId) {
    return this.groups.filter((v) => (v.city === cityId)); // .concat([{ name: t`未分组`, city: cityId, regions: [] }]);
  }

  set selectedName(value) {
    this._selected = this.getGroup(value);
  }

  get selected() {
    return this._selected;
  }

  get regions() { // 当前分组下的所有区域
    if (!this._selected) {
      return [];
    }
    return this.regionsForGroup(this._selected.name).filter((r) => {
      if (!this.search.keyword) return true;
      return r.name.includes(this.search.keyword) || r.itemId.includes(this.search.keyword);
    });
  }


  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    // this.query({ page: 0 });
  }
}
